import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'


// 创建路由规则
const routes: any = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/regLogin',
    name: 'regLogin',
    component: () => import('../views/regLogin.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    children: [
      {
        path: 'prod',
        component: () => import('../views/prodList.vue')
      },
      {
        path: 'brand',
        component: () => import('../views/brandList.vue')
      },
      {
        path: 'type',
        component: () => import('../views/typeList.vue')
      },
      {
        path: 'order',
        component: () => import('../views/orderList.vue')
      },
      {
        path: 'prodDetail/:prodId',
        component: () => import('../views/ProdDetail.vue')
      },
      {
        path: 'GroupActive',
        component: () => import('../views/GroupActive.vue')
      },
      {
        path: 'join',
        component: () => import('../views/GroupJoin.vue')
      },
      {
        path: 'group',
        component: () => import('../views/GroupList.vue')
      },
      {
        path: 'GroupOrder',
        component: () => import('../views/GroupOrderList.vue')
      },
      {
        path: 'active',
        component: () => import('../views/ActiveList.vue')
      },
    ]
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (About.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/line',
    name: 'line',
    component: () => import('../views/DemoLineView.vue')
  },
  {
    path: '/map',
    name: 'map',
    component: () => import('../views/DemoAmapView.vue')
  },
];

// 创建router实例
const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  if (to.name == 'login') {
    next()
    return;
  }
  if (to.name == 'regLogin') {
    next()
    return;
  }
  // 检查用户是否认证，例如检查token
  let token = window.sessionStorage.getItem('token');
  // to.name
  if (!token) {
    next({ path: '/login', query: { redirect: to.fullPath } });
  }
  else {
    next();
  }
});

export default router
